package cn.org.eshow.webapp.action;

import cn.org.eshow.bean.query.ProductCategoryQuery;
import cn.org.eshow.model.ProductCategory;
import cn.org.eshow.service.ProductCategoryManager;
import cn.org.eshow.webapp.action.response.ProductCategoryResponse;
import cn.org.eshow.webapp.util.RenderUtil;
import org.apache.struts2.convention.annotation.AllowedMethods;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类API接口
 */
@AllowedMethods({"getAllCategory"})
public class ProductCategoryAction extends ApiBaseAction<ProductCategory> {

    private static final long serialVersionUID = 1L;

    @Autowired
    private ProductCategoryManager productCategoryManager;

    private ProductCategory productCategory = new ProductCategory();
    private List<ProductCategory> productCategories = new ArrayList<ProductCategory>();
    private ProductCategoryQuery query = new ProductCategoryQuery(true);


    /**
     * 获取指定星球 顶部分类集合
     */
    public void getAllCategory() {
        List<ProductCategory> topProductCategories = productCategoryManager.list(new ProductCategoryQuery(Boolean.TRUE, Boolean.TRUE));//获取顶级分类
        List<ProductCategoryResponse> responses = new ArrayList<ProductCategoryResponse>();
        for (ProductCategory topCategory : topProductCategories) {
            ProductCategoryResponse response = new ProductCategoryResponse(topCategory);
            response.setChildProductCategories(myChild(topCategory));
            responses.add(response);
        }
        RenderUtil.list("获取成功", "productCategories", responses);
    }


    /**
     * 通过传入的分类,查询其子类。并添加到List中
     */
    private List<ProductCategoryResponse> myChild(ProductCategory parentCategory) {
        List<ProductCategoryResponse> responses = new ArrayList<ProductCategoryResponse>();
        List<ProductCategory> childMedicineCategories = productCategoryManager.list(new ProductCategoryQuery(Boolean.TRUE, parentCategory.getId()));//获取指定子分类
        for (ProductCategory category : childMedicineCategories) {
            ProductCategoryResponse response = new ProductCategoryResponse(category);
            if (category.getChildrenSize() > 0) {
                response.setChildProductCategories(myChild(category));
            }
            responses.add(response);
        }
        return responses;
    }




    public ProductCategory getProductCategory() {
        return productCategory;
    }

    public void setProductCategory(ProductCategory productCategory) {
        this.productCategory = productCategory;
    }

    public List<ProductCategory> getProductCategories() {
        return productCategories;
    }

    public void setProductCategories(List<ProductCategory> productCategories) {
        this.productCategories = productCategories;
    }

    public ProductCategoryQuery getQuery() {
        return query;
    }

    public void setQuery(ProductCategoryQuery query) {
        this.query = query;
    }
}